package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.ThreadPoolUtils;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.service.ProductSkuService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper , ProductSku>
implements ProductSkuService {
    @Resource
    RedisTemplate redisTemplate;
    //保证数据一致性： 更新sku数据时，无论它是否有缓存，更新成功时 删除redis中的指定缓存
//    @CacheEvict(value = "spzx:channel:cache"  , key ="'item:'+#productSku.id")
    @Override
    public void updateSkuById(ProductSku productSku) {
        //1-删除productSku的商品缓存
        String key = "spzx:mycache:["+productSku.getId()+"]";
        redisTemplate.delete(key);
        baseMapper.updateById(productSku);
        //2-修改成功后 延迟删除redis中的缓存
        ThreadPoolUtils.getPool()
                .execute(()->{
                    try {
                        Thread.sleep(1000);
                        //延迟1秒钟执行删除缓存的操作
                        redisTemplate.delete(key);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
    }
}
